package df.servlet.process;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import df.bean.db.conn.DBConn;
import df.bean.db.conn.DBConnection;
import df.bean.db.table.Batch;
import df.bean.db.table.PaymentMonthly;
import df.bean.expense.ExpenseSummaryBean;
import df.bean.obj.doctor.CareProvider;
import df.bean.obj.doctor.DoctorList;
import df.bean.obj.util.JDate;
import df.bean.obj.util.Variables;
import df.bean.process.ProcessBankTMBPaymentMonthly;

public class ProcessAllMonthlySrvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private DoctorList doctorList = null;
    private DoctorList drList = null;
    private ExpenseSummaryBean  esb;
    private DBConnection conn = null;
    private PaymentMonthly pm = null;
    private int countNum = 0;
    private DBConn cdb = null;
    private String[] strArray =null;
    private String d = "";
    private String mm = "";
    private String year = "";
    private String bothJson= "";
    private Batch batch = null;
    private ProcessBankTMBPaymentMonthly pbm = null;
    
    public void doProcess(HttpServletRequest request, HttpServletResponse response){
    	String mode = request.getParameter("mode");
    	String date = request.getParameter("date");
		String hospitalCode = request.getParameter("hospitalCode");
    	if(request.getParameter("mode") != null){
    		if(request.getParameter("date") != null){
	        	this.strArray = date.split("\\/");
	        	this.d = this.strArray[0];
	        	this.mm = this.strArray[1];
	        	this.year = this.strArray[2];
	        	
	        	if(this.mm.equals("01")){
	        		this.mm = "12";
	        		this.year =  Integer.toString(Integer.parseInt(this.year)-1);
	        	}else{
	        		if(this.mm.substring(0,1).equals("0")){
		        		this.mm = "0"+Integer.toString(Integer.parseInt(this.mm)-1);
	        		}else{
		        		this.mm = Integer.toString(Integer.parseInt(this.mm)-1);
		        		if(this.mm.length()==1){
		        			this.mm = "0"+this.mm;
		        		}
	        		}
	        	}
    		}
	    	if(mode.equals("getDoctor")){
	    		//System.out.println("mode = " + mode);
				DBConn dbConn = new DBConn();
				String bothJson= "{ \"listDoctorCode\" : [";
				String sql = "";
				HashMap<String, String> hashData = new HashMap<String, String>();
		        sql="SELECT CODE FROM DOCTOR WHERE HOSPITAL_CODE = '"+hospitalCode+"'";
		        System.out.println("Get Doctor");
		        ArrayList<HashMap<String, String>> arrData = dbConn.listQueryData(sql);
		        dbConn.closeDB("");
		        if(arrData.size() > 0){
		        	for(int i=0;i<arrData.size();i++){
		        		hashData = arrData.get(i);
		        		bothJson += "{\"doctorCode\" : \""+hashData.get("CODE")+"\"}, ";
		        	}
		        }
	    		try{
			       //write Json	
	    			bothJson = bothJson.substring(0, bothJson.length()-2);
					bothJson += "]}";
			        response.setContentType("application/json"); 
					response.setCharacterEncoding("utf-8"); 
					response.getWriter().write(bothJson);
				}catch(IOException e){
					System.out.println("Error Message => " + e.getMessage());
				}
			
	    	}else if(mode.equals("processMonthly")){ // ====== Mouthly Calulate ======
		    	String doctorCode = request.getParameter("doctorCode");
		    	int count = Integer.parseInt(request.getParameter("count"));
		    	int maxSize = Integer.parseInt(request.getParameter("maxSize"))-1;
		    	
		    	if(count == 0){
			    	System.out.println(" ====== Start Mouthly Calulate ======");
			    	this.conn = new DBConnection();
			    	this.conn.connectToLocal();
		    		this.drList = new DoctorList(hospitalCode, this.conn);
		    		this.drList.newAllDoctor(hospitalCode);
		    		countNum = 0;
		    	}
			    	this.setDoctorList(this.drList);
			    	if (!MonthlyCalculate(this.year, this.mm, hospitalCode, doctorCode)) {
	                }else{countNum++;}
	                bothJson = "{\"count\" : \""+countNum+"\",\"lastData\" : \"N\"}";
	            if(maxSize == count){
	            	System.out.println(" ====== End Mouthly Calulate ======");
	                bothJson = "{\"count\" : \""+countNum+"\",\"lastData\" : \"Y\"}";
	                this.conn.Close();
	            }
				try {
			        response.setContentType("application/json"); 
					response.setCharacterEncoding("utf-8"); 
					response.getWriter().write(bothJson);
				} catch (IOException e) {
					System.out.println("Error Message = > " + e.getMessage());
				}
	        	
		    }else if(mode.equals("expenseCalulate")){ // ====== Expense Calulate ======
		    	iniExpenseCalulate();
		    	String processType = request.getParameter("processType");
		    	int count = Integer.parseInt(request.getParameter("count"));
		    	if(count == 0){
		    		countNum = 0;
		    	}
		    	if(this.esb.summaryProcess(this.mm, this.year, hospitalCode, processType)){
		    		countNum++;
	                bothJson = "{\"count\" : \""+countNum+"\"}";
		    	}

				try {
			        response.setContentType("application/json"); 
					response.setCharacterEncoding("utf-8"); 
					response.getWriter().write(bothJson);
					this.conn.Close();
				} catch (IOException e) {
					System.out.println("Error Message = > " + e.getMessage());
				}
		    }else if(mode.equals("paymentSummmary")){ // ====== Payment Summmary =====
				String doctorCode = request.getParameter("doctorCode");
				int count = Integer.parseInt(request.getParameter("count"));
		    	int maxSize = Integer.parseInt(request.getParameter("maxSize"))-1;
				this.bothJson= "";

				try {
				if(count == 0){
					System.out.println("====== Start Process Payment Monthly =====");
					this.conn = new DBConnection();
					this.conn.connectToLocal();
					pm = new PaymentMonthly(this.conn);
				    countNum = 0;
				    maxSize = Integer.parseInt(request.getParameter("maxSize"))-1;
				}
				
                if (!Calculate(hospitalCode, doctorCode, JDate.saveDate(date))) {}
                else{countNum++;}
		        bothJson = "{\"count\" : \""+countNum+"\",\"lastData\" : \"N\"}";
				if(count == maxSize){
					this.conn.getConnection().close();
					pm = null;
			        bothJson = "{\"count\" : \""+countNum+"\",\"lastData\" : \"Y\"}";
					System.out.println("====== End Process Payment Monthly ======");
				}
			        response.setContentType("application/json"); 
					response.setCharacterEncoding("utf-8"); 
					response.getWriter().write(bothJson);
				} catch (IOException e) {
					System.out.println("Error Message = > " + e.getMessage());
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}else if(mode.equals("bankPayment")){
		        String payDate = JDate.saveDate(request.getParameter("date"));
		        String recNo = request.getParameter("recNo");
			    this.countNum = 0;

			    this.conn = new DBConnection();
			    this.conn.connectToLocal();
		        
		        if (recNo.equalsIgnoreCase("2")) {       
		            newObject(hospitalCode);
		        }
		        if (pbm.run(Batch.getYyyy(), Batch.getMm(), payDate, PaymentMonthly.PAYMENT_TYPE_DF, hospitalCode)) {
		        	countNum = 1;
		        }else countNum = 0;

	        	bothJson = "{\"count\" : \""+countNum+"\"}";
				try {
			        response.setContentType("application/json"); 
					response.setCharacterEncoding("utf-8"); 
					response.getWriter().write(bothJson);
					this.conn.Close();
				} catch (IOException e) {
					System.out.println("Error Message = > " + e.getMessage());
				}
			}
    	}else{
    		System.out.println("Mode is Null Cannot Process!!!");
    	}
    }
    
    private void newObject(String hos) {
        batch = new Batch(hos, conn);
        pbm = new ProcessBankTMBPaymentMonthly(conn);
    }
    public void iniExpenseCalulate(){
    	this.conn = new DBConnection();
    	this.conn.connectToLocal();
    	this.cdb = new DBConn(this.conn.getConnection());
        try {
        	this.cdb.setStatement();
        	this.esb = new ExpenseSummaryBean(this.cdb);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
	public boolean MonthlyCalculate(String YYYY, String MM, String hospitalCode, String doctorCode) {
        boolean ret = true;
        CareProvider careProvider = null;
        careProvider = this.getDoctorList().getDoctor(doctorCode);
        
        if (careProvider != null) {
            if (careProvider.computeTransMonthly()) {
                ret = true;    
            }else {  
                ret = false;   
            }
        }else{
        }
        return ret;
    }
    public boolean Calculate(String hospitalCode, String doctorCode, String payDate) {
        boolean ret = false;
        if (pm.insertToPaymentSummmary(hospitalCode, payDate, doctorCode)>-1) {
            ret = true;    
        }else {  
            ret = false;   
        }
        return ret;
    } 
    
    private DoctorList getDoctorList() {
        return doctorList;
    }

    private void setDoctorList(DoctorList doctorList) {
        this.doctorList = doctorList;
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
}
